package com.rags.chess.io;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import com.rags.chess.base.Color;
import com.rags.chess.game.Game;
import com.rags.chess.move.Move;

public class PgnWriter {
	public static String LINE_SEPARATOR = System.getProperty("line.separator");

	public static void writeGameToFile(Game game, String filename) throws IOException {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(String.format("[Event \"%s\"]%s", game.getEvent(), LINE_SEPARATOR));
		stringBuilder.append(String.format("[Date \"%s\"]%s", game.getDate(), LINE_SEPARATOR));
		stringBuilder.append(String.format("[White \"%s\"]%s", game.getPlayer(Color.WHITE).getName(), LINE_SEPARATOR));
		stringBuilder.append(String.format("[Black \"%s\"]%s", game.getPlayer(Color.BLACK).getName(), LINE_SEPARATOR));
		stringBuilder.append(String.format("[Result \"%s\"]%s", game.getResult(), LINE_SEPARATOR));
		stringBuilder.append(String.format("[Opening \"%s\"]%s", game.getOpening(), LINE_SEPARATOR));
		stringBuilder.append(String.format("[ECO \"%s\"]%s", game.getECO(), LINE_SEPARATOR));
		stringBuilder.append(String.format("[Board \"%s\"]%s", game.getBoard(), LINE_SEPARATOR));
		stringBuilder.append(String.format("[Variant \"%s\"]%s", game.getVariant(), LINE_SEPARATOR));
		stringBuilder.append(String.format("[PlyCount \"%d\"]%s%s", game.getPlyCount(), LINE_SEPARATOR, LINE_SEPARATOR));
		List<Move> moves = game.getMoves();
		for (int i=0; i<moves.size(); i++) {
			if (i%2 == 0)
				stringBuilder.append(String.format("%d.%s ", ((i/2)+1), moves.get(i).getNotation()));
			else
				stringBuilder.append(String.format("%s ", moves.get(i).getNotation()));
		}
		stringBuilder.append(String.format("%s%s ", game.getResult(), LINE_SEPARATOR));
		
		BufferedWriter bufferedWriter = null;
		try {
			bufferedWriter = new BufferedWriter(new FileWriter(filename, true));
			bufferedWriter.write(stringBuilder.toString());
		} finally {
			bufferedWriter.close();
		}
	}
}
